package com.lzm.wx.controller;

import com.lzm.bean.*;
import com.lzm.mvc.ResponseBody;
import com.lzm.service.CourierService;
import com.lzm.service.ExpressService;
import com.lzm.service.UserService;
import com.lzm.util.JSONUtil;
import com.lzm.util.RandomUtil;
import com.lzm.util.SMSUtil;
import com.lzm.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class UserController {

    @ResponseBody("/wx/loginSms.do")
    public String sendSms(HttpServletRequest request, HttpServletResponse response) {
        String userPhone = request.getParameter("userPhone");
        String code = RandomUtil.getCode() + "";
        //boolean flag = SMSUtil.loginSMS(userPhone,code);
        boolean flag = true;
        Message msg = new Message();
        if (flag) {
            //短信发送成功
            msg.setStatus(0);
            msg.setResult("验证码已发送，请查收！");
        } else {
            //短信发送失败
            msg.setStatus(-1);
            msg.setResult("验证码发送失败，请检查手机号或稍后再试");
        }
        //UserUtil.setLoginSms(request.getSession(),userPhone,code);
        UserUtil.setLoginSms(request.getSession(), userPhone, "123456");
        String json = JSONUtil.toJSON(msg);
        return json;

    }

    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String userPhone = request.getParameter("userPhone");
        String usercode = request.getParameter("code");
        String sysCode = UserUtil.getLoginSms(request.getSession(), userPhone);
        Message msg = new Message();
        if (sysCode == null) {
            //这手机号未获取短信
            msg.setStatus(-1);
            msg.setResult("手机号码未获取短信");
        } else if (sysCode.equals(usercode)) {
            //这里手机号和短信一致，登录成功
            //TODO 判断是快递员还是用户，如果都不是则默认注册为用户，如果是快递员则以快递员身份登录
            User user1 = UserService.findByUserPhone(userPhone);
            Courier courier1 = CourierService.findByCourierPhone(userPhone);
            if (user1 == null && courier1 == null) {
                //数据库中没有该登录信息，即不是用户也不是快递员，默认注册为用户
                msg.setStatus(0);
                msg.setResult("该手机号未注册，正为您使用手机号注册一个新账号");
                User u = new User();
                u.setUserPhone(userPhone);
                UserService.insert(u);
                UserUtil.setWxUser(request.getSession(), u);
            } else if (user1 != null && courier1 == null) {
                //用户
                msg.setStatus(0);
                msg.setResult("用户登录成功！");
                UserUtil.setWxUser(request.getSession(), user1);
            } else if (user1 == null && courier1 != null) {
                msg.setStatus(1);
                msg.setResult("快递员登录成功！");
                UserUtil.setWxUser(request.getSession(), courier1);
            }
        } else {
            //这里验证码不一致
            msg.setStatus(-2);
            msg.setResult("验证码不一致，请检查");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/userInfo.do")
    public String userInfo(HttpServletRequest request, HttpServletResponse response) {
        Object loginUser = UserUtil.getWxUser(request.getSession());
        boolean isUser = loginUser instanceof User;
        Message msg = new Message();
        if (isUser) {
            msg.setStatus(0);
            msg.setResult(((User) loginUser).getUserPhone());
        } else {
            msg.setStatus(1);
            msg.setResult(((Courier) loginUser).getCourierPhone());
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/loginOut.do")
    public String loginOut(HttpServletRequest request, HttpServletResponse response) {
        //1. 销毁session
        request.getSession().invalidate();
        //2.给客户端回复消息
        Message msg = new Message();
        msg.setStatus(0);
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/userName.do")
    public String userName(HttpServletRequest request, HttpServletResponse response) {
        Object wxUser = UserUtil.getWxUser(request.getSession());
        boolean isUser = wxUser instanceof User;
        Message msg = new Message();
        if (isUser) {
            msg.setStatus(0);
            msg.setResult(((User) wxUser).getUserName());
        } else {
            msg.setStatus(1);
            msg.setResult(((Courier) wxUser).getCourierName());
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/updateSms.do")
    public String updateSms(HttpServletRequest request, HttpServletResponse response) {
        String userPhone = request.getParameter("userPhone");
        String code = RandomUtil.getCode() + "";
        //boolean flag = SMSUtil.loginSMS(userPhone,code);
        boolean flag = true;
        Message msg = new Message();
        if (flag) {
            //短信发送成功
            msg.setStatus(0);
            msg.setResult("验证码已发送，请查收！");
        } else {
            //短信发送失败
            msg.setStatus(-1);
            msg.setResult("验证码发送失败，请检查手机号或稍后再试");
        }
        //UserUtil.setLoginSms(request.getSession(),userPhone,code);
        UserUtil.setUpdateSms(request.getSession(), userPhone, "123456");
        String json = JSONUtil.toJSON(msg);
        return json;

    }

    @ResponseBody("/wx/update.do")
    public String update(HttpServletRequest request, HttpServletResponse response) {
        String newName = request.getParameter("newName");
        String newPhone = request.getParameter("newPhone");
        String verify = request.getParameter("verify");
        String sysCode = UserUtil.getUpdateSms(request.getSession(), newPhone);
        Message msg = new Message();
        if (sysCode == null) {
            msg.setStatus(-1);
            msg.setResult("手机号码未获取短信");
        } else if (sysCode.equals(verify)) {
            Object wxUser = UserUtil.getWxUser(request.getSession());
            if (wxUser instanceof User) {
                User oldUser = UserService.findByUserPhone(((User) wxUser).getUserPhone());
                int id = oldUser.getId();
                oldUser.setUserName(newName);
                oldUser.setUserPhone(newPhone);
                boolean flag = UserService.update(id, oldUser);
                if (flag) {
                    msg.setStatus(0);
                    msg.setResult("修改成功");
                } else {
                    msg.setStatus(-3);
                    msg.setResult("修改失败");
                }
            } else if (wxUser instanceof Courier) {
                Courier oldUser = CourierService.findByCourierPhone(((Courier) wxUser).getCourierPhone());
                int id = oldUser.getId();
                oldUser.setCourierName(newName);
                oldUser.setCourierPhone(newPhone);
                boolean flag = CourierService.update(id, oldUser);
                if (flag) {
                    msg.setStatus(0);
                    msg.setResult("修改成功");
                } else {
                    msg.setStatus(-3);
                    msg.setResult("修改失败");
                }
            }
        }else {
            // 验证码不一致
            msg.setStatus(-2);
            msg.setResult("验证码不一致，请检查");
        }
            String json = JSONUtil.toJSON(msg);
            return json;
}
    @ResponseBody("/wx/checkUser.do")
    public String checkUser(HttpServletRequest request, HttpServletResponse response) {
        Object loginUser = UserUtil.getWxUser(request.getSession());
        boolean isUser = loginUser instanceof User;
        Message msg = new Message();
        if (isUser) {
            String userPhone = ((User) loginUser).getUserPhone();
            User user = UserService.findByUserPhone(userPhone);
            if (user.getUserPassword() == null){
                msg.setStatus(-1);
                msg.setResult("该用户未认证");
            }else {
                msg.setStatus(0);
                msg.setResult("该用户已认证");
            }

        } else {
            String courierPhone = ((Courier) loginUser).getCourierPhone();
            Courier courier = CourierService.findByCourierPhone(courierPhone);
            if (courier.getCourierPassword() == null){
                msg.setStatus(-1);
                msg.setResult("该快递员未认证");
            }else {
                msg.setStatus(1);
                msg.setResult("该快递员已认证");
            }
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/check.do")
    public String check(HttpServletRequest request, HttpServletResponse response) {
        String newName = request.getParameter("newName");
        String newPhone = request.getParameter("newPhone");
        String password = request.getParameter("password");
        String verify = request.getParameter("verify");
        String sysCode = UserUtil.getUpdateSms(request.getSession(), newPhone);
        Message msg = new Message();
        if (sysCode == null) {
            msg.setStatus(-1);
            msg.setResult("手机号码未获取短信");
        } else if (sysCode.equals(verify)) {
            Object wxUser = UserUtil.getWxUser(request.getSession());
            if (wxUser instanceof User) {
                User oldUser = UserService.findByUserPhone(((User) wxUser).getUserPhone());
                int id = oldUser.getId();
                oldUser.setUserName(newName);
                oldUser.setUserPhone(newPhone);
                oldUser.setUserPassword(password);
                boolean flag = UserService.update(id, oldUser);
                if (flag) {
                    msg.setStatus(0);
                    msg.setResult("修改成功");
                } else {
                    msg.setStatus(-3);
                    msg.setResult("修改失败");
                }
            } else if (wxUser instanceof Courier) {
                Courier oldUser = CourierService.findByCourierPhone(((Courier) wxUser).getCourierPhone());
                int id = oldUser.getId();
                oldUser.setCourierName(newName);
                oldUser.setCourierPhone(newPhone);
                oldUser.setCourierPassword(password);
                boolean flag = CourierService.update(id, oldUser);
                if (flag) {
                    msg.setStatus(0);
                    msg.setResult("修改成功");
                } else {
                    msg.setStatus(-3);
                    msg.setResult("修改失败");
                }
            }
        }else {
            // 验证码不一致
            msg.setStatus(-2);
            msg.setResult("验证码不一致，请检查");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/find.do")
    public String find(HttpServletRequest request, HttpServletResponse response){
        Object loginUser = UserUtil.getWxUser(request.getSession());
        boolean isUser = loginUser instanceof User;
        Message msg = new Message();
        if (isUser) {
            String userPhone = ((User) loginUser).getUserPhone();
            User user = UserService.findByUserPhone(userPhone);
            msg.setStatus(0);
            msg.setResult("用户认证信息");
            msg.setData(user);
        } else {
            String courierPhone = ((Courier) loginUser).getCourierPhone();
            Courier courier = CourierService.findByCourierPhone(courierPhone);
            msg.setStatus(1);
            msg.setResult("快递员认证信息");
            msg.setData(courier);
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }
    @ResponseBody("/wx/lazyboardTotal.do")
    public String lazyboardTotal(HttpServletRequest request, HttpServletResponse response){
        List<Express> eList = ExpressService.findAll(false,0,0);
        List<User> userList = UserService.findAll(false,0,0);
        List<LazyBoardUser> result = new ArrayList<>();
        for (User u : userList){
            List<Express> byUserPhone = ExpressService.findByUserPhone(u.getUserPhone());
            LazyBoardUser lu = new LazyBoardUser(u.getUserPhone(), u.getUserName()==null?"新用户":u.getUserName(), byUserPhone.size());
            result.add(lu);
        }
        Collections.sort(result);
        Message msg = new Message();
        if (!result.isEmpty()){
            msg.setStatus(0);
            msg.setResult("查询成功");
            msg.setData(result);
        }else{
            msg.setStatus(-1);
            msg.setResult("查询失败");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/lazyboardYear.do")
    public String lazyboardYear(HttpServletRequest request, HttpServletResponse response){
        List<User> userList = UserService.findAll(false, 0, 0);
        List<LazyBoardUser> result = new ArrayList<>();

        for (User u : userList){
            List<Express> byUserPhone = ExpressService.findAllAmongYearByPhone(u.getUserPhone());
            LazyBoardUser lu = new LazyBoardUser(u.getUserPhone(), u.getUserName()==null?"新用户":u.getUserName(), byUserPhone.size());
            result.add(lu);
        }

        Collections.sort(result);

        Message msg = new Message();
        if (!result.isEmpty()){
            msg.setStatus(0);
            msg.setResult("查询成功");
            msg.setData(result);
        }else{
            msg.setStatus(-1);
            msg.setResult("查询失败");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/lazyboardMonth.do")
    public String lazyboardMonth(HttpServletRequest request, HttpServletResponse response){
        List<User> userList = UserService.findAll(false, 0, 0);
        List<LazyBoardUser> result = new ArrayList<>();

        for (User u : userList){
            List<Express> byUserPhone = ExpressService.findAllAmongMonthByPhone(u.getUserPhone());
            LazyBoardUser lu = new LazyBoardUser(u.getUserPhone(), u.getUserName()==null?"新用户":u.getUserName(), byUserPhone.size());
            result.add(lu);
        }

        Collections.sort(result);

        Message msg = new Message();
        if (!result.isEmpty()){
            msg.setStatus(0);
            msg.setResult("查询成功");
            msg.setData(result);
        }else{
            msg.setStatus(-1);
            msg.setResult("查询失败");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }
}